package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.Destination;
import cn.wolfcode.wolf2w.domain.Strategy;
import cn.wolfcode.wolf2w.domain.StrategyCatalog;
import cn.wolfcode.wolf2w.domain.StrategyTheme;
import cn.wolfcode.wolf2w.query.StrategyQuery;
import cn.wolfcode.wolf2w.redis.vo.StrategyStatisVO;
import cn.wolfcode.wolf2w.repository.StrategyRepository;
import cn.wolfcode.wolf2w.service.IDestinationService;
import cn.wolfcode.wolf2w.service.IStrategyCatalogService;
import cn.wolfcode.wolf2w.service.IStrategyService;
import cn.wolfcode.wolf2w.service.IStrategyThemeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * Created by 甘静斌 on 2020-08-07 13:41
 */
@Service
//@Transactional
public class StrategyServiceImpl implements IStrategyService {

    @Autowired
    private StrategyRepository repository;

    @Autowired
    private MongoTemplate template;

    @Autowired
    private IStrategyCatalogService strategyCatalogService;

    @Autowired
    private IStrategyThemeService strategyThemeService;

    @Autowired
    private IStrategyService strategyService;

    @Autowired
    private IDestinationService destinationService;

    @Override
    public void save(Strategy strategy) {
        strategy.setId(null);
        repository.save(strategy);
    }

    @Override
    public void update(Strategy strategy) {

        repository.save(strategy);
    }

    @Override
    public void delete(String id) {
        repository.deleteById(id);
    }

    @Override
    public Strategy get(String id) {
        return repository.findById(id).orElse(null);
    }

    @Override
    public List<Strategy> list() {


        return repository.findAll();
    }

    @Override
    public Page<Strategy> query(StrategyQuery qo) {


        //查询封装类
        Query query = new Query();

        //页面显示查看全部
        if (StringUtils.hasLength(qo.getDestId())){

            query.addCriteria(Criteria.where("destId").is(qo.getDestId()));
        }

        if (StringUtils.hasLength(qo.getThemeId())){

            query.addCriteria(Criteria.where("themeId").is(qo.getThemeId()));
        }

        //分页需要的数据: total -- 所有数据
        long total = template.count(query, Strategy.class);
        if (total == 0){
            return Page.empty();
        }
        //分页数据 , currentPage , pageSite
        Pageable pageable = PageRequest.of(qo.getCurrentPage()-1,qo.getPageSize() ,Sort.Direction.ASC,"_id");
        query.with(pageable);
        //当前页显示的数据
        List<Strategy> list = template.find(query, Strategy.class);

        //list Pageable total 封装三个数据,返回给页面
        return new PageImpl(list,pageable,total);
    }

    /**
     * 后端编辑操作,注意冗余字段
     * 编辑时注意参数丢失问题
     * @param strategy
     */
    @Override
    public void saveOrUpdate(Strategy strategy) {


        StrategyCatalog catalog = strategyCatalogService.get(strategy.getCatalogId());
        System.out.println(catalog);
        //目的地id  destId
        strategy.setDestId(catalog.getDestId());
        //目的地名称  destName
        strategy.setDestName(catalog.getDestName());
        //主题名称   themName
        StrategyTheme theme = strategyThemeService.get(strategy.getThemeId());
        strategy.setThemeName(theme.getName());
        //分类名称  catalogName
        strategy.setCatalogName(catalog.getName());
        //是否国外
        List<Destination> toasts = destinationService.findToasts(catalog.getDestId());
        if (toasts != null && toasts.size() > 0){
            Destination dest = toasts.get(0);
            strategy.setIsabroad("中国".equals(dest.getName()) ? Strategy.ABROAD_NO : Strategy.ABROAD_YES);
        }
        //判断是否有id,有则修改,无则添加
        if (StringUtils.hasLength(strategy.getId())){

            //先查询
            Strategy temp = this.get(strategy.getId());
            //替换
            strategy.setCreateTime(temp.getCreateTime());
            strategy.setViewnum(temp.getViewnum());
            strategy.setSharenum(temp.getSharenum());
            strategy.setFavornum(temp.getFavornum());
            strategy.setReplynum(temp.getReplynum());
            strategy.setThumbsupnum(temp.getThumbsupnum());


            this.update(strategy);
        }else {
            //创建时间
            strategy.setCreateTime(new Date());
            this.save(strategy);
        }
    }

    //更改状态是否下架
    @Override
    public void changeState(String id, int state) {

        Query query = new Query();

        query.addCriteria(Criteria.where("_id").is(id));
        Update update = new Update();
        update.set("state",state );


        template.updateMulti(query,update ,Strategy.class );


    }

    //添加操作
    @Override
    public Strategy getId(String id) {

        if (StringUtils.hasLength(id)){

            Strategy strategy = this.get(id);
            return strategy;
        }
        return null;
    }

    /**
     * 前端攻略点击量前三列表
     * @param destId
     * @return
     */
    @Override
    public List<Strategy> queryByViewnum(String destId) {
        //根据点击量查询并分页,封装到list集合中,再返回给页面
        Pageable pageable = PageRequest.of(0,3 ,Sort.Direction.DESC,"viewnum" );

        List<Strategy> list = repository.findByDestId(destId,pageable);

        return list;
    }

    @Override
    public void updateStratisVo(StrategyStatisVO vo) {

        Query query = new Query();
        query.addCriteria(Criteria.where("_id").is(vo.getStrategyId()));
        Update update = new Update();
        update.set("favornum",vo.getFavornum());
        update.set("replynum",vo.getReplynum());
        update.set("thumbsupnum",vo.getThumbsupnum());
        update.set("viewnum",vo.getViewnum());
        update.set("sharenum",vo.getSharenum());

        template.updateMulti(query,update ,Strategy.class );
    }

    @Override
    public List<Strategy> queryByDestId(String id) {
        return repository.findByDestId(id,null );
    }

   /* @Override
    public List<Strategy> queryByDestId(StrategyQuery qo) {

        Pageable pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(), Sort.Direction.ASC, "_id");

        List<Strategy> list = repository.findByDestId(qo.getDestId(),pageable);

        return list;
    }
*/
}
